import UIKit
import Flutter
import BUAdSDK
import AdSupport
import AppTrackingTransparency

var splashAd : BUSplashAd?
var bridgeChannel : FlutterMethodChannel?


@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate ,BUSplashAdDelegate{
    
  override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      GeneratedPluginRegistrant.register(with: self)
     
      let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
      bridgeChannel = FlutterMethodChannel(name: "sing.top/rth", binaryMessenger: controller.binaryMessenger)
      bridgeChannel?.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
          if (call.method == "getNetParams") {
              let network = "wifi"
              let model = "苹果14"
              let version = "1.0.4"
              let device_id = "19231241241231"
              result("?os=1&network=\(network)&model=\(model)&version=\(version)&device_id=\(device_id)&device=iOS")

    //           result(swiftBridge.getNetParams(str: call.arguments as! String))
          } else if (call.method == "setData") { // flutter 传过来的数据
              // 安全地解析参数
              if let arguments = call.arguments as? [String: Any],
                 let token = arguments["token"] as? String,
                 let phone = arguments["phone"] as? String,
                 let channelId = arguments["channel_id"] as? Int {
                     // 处理接收到的参数
                  print("token = \(token) , phone = \(phone) , channelId = \(channelId)")
              } else { // 参数不完整或格式错误
                  print("参数不完整或格式错误")
              }
          } else if (call.method == "loadAd") { // 加载广告
//              let adController = AdController()
//              adController.modalPresentationStyle = .fullScreen
//              adController.onClose = {
//                  bridgeChannel.invokeMethod("loadAdOver", arguments: "200") { (result) in
//
//                  }
//              }
//
//              if let viewController = UIApplication.shared.keyWindow?.rootViewController {
//                  viewController.present(adController, animated: true, completion: nil)
//              }
            // 暂时没有广告
              self.loadAdOver()
              
//              self.initAd()
          } else if (call.method == "toFace") { // 人脸识别
              if let arguments = call.arguments as? [String: Any],
                 let name = arguments["name"] as? String,
                 let identityNum = arguments["identityNum"] as? String{
                     // 处理接收到的参数
                  print("name = \(name) , phone = \(identityNum)")


              } else { // 参数不完整或格式错误
                  print("参数不完整或格式错误")
              }
          } else if (call.method == "scanBank") { // 银行卡识别
              // TODO
          } else if (call.method == "scanIdFront") { // 身份证头像面
              // TODO
          } else if (call.method == "scanIdBack") { // 身份证国徽
              // TODO
          } else {
              result(FlutterMethodNotImplemented)
          }
      }
      
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    
    
    
    
    
    /******************** 初始化 ********************/
    @objc func initAd() {
        let configuration = BUAdSDKConfiguration()
        configuration.appID = "5538224" // 设置APPID 5524370 android的   5538224 iOS的
        configuration.debugLog = true // 设置日志输出
        configuration.useMediation = false // 是否使用聚合

        // 初始化
        BUAdSDKManager.start(asyncCompletionHandler:{ success, error in
            if success { // 处理成功之后的逻辑
                print("---------------------------------------------------------\n SDK初始化成功")
                self.loadSplashAd()
            } else{
                self.loadAdOver()
            }
        })
    }
    
    /******** 开屏广告配置 *********/
    func loadSplashAd() -> Void {
        let slot = BUAdSlot()
        slot.id = "889243899"
        let splashAd1 = BUSplashAd(slot: slot, adSize: CGSize.zero)
        splashAd1.delegate = self
        splashAd = splashAd1

        splashAd?.loadData()
    }
    
    /******** 开屏广告回调处理 *********/
    // 加载成功
    func splashAdLoadSuccess(_ splashAd: BUSplashAd) {
        // 使用应用keyWindow的rootViewController（接入简单，推荐）
        if let keyWindow = UIApplication.shared.keyWindow {
            let rootViewController = keyWindow.rootViewController
            // 在这里可以使用 rootViewController
            
            
            splashAd.showSplashView(inRootViewController: rootViewController!)

            
        } else {
            // 处理无法获取 keyWindow 的情况
        }
        
 

//        splashAd.showSplashView(inRootViewController: adController)
        
        print("1111111111111111111111, 加载成功")

    }

    // 加载失败
    func splashAdLoadFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("1111111111111111111111, 加载失败")
        print(error ?? "没用错误信息")
        loadAdOver()
    }

    // 广告即将展示
    func splashAdWillShow(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告即将展示")
    }

    // 广告被点击
    func splashAdDidClick(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告被点击")
    }

    // 广告被关闭
    func splashAdDidClose(_ splashAd: BUSplashAd, closeType: BUSplashAdCloseType) {
        // 按照实际情况决定是否销毁广告对象
        splashAd.mediation?.destoryAd()
        print("1111111111111111111111, 广告被关闭")
        loadAdOver()
    }

    // 广告展示失败
    func splashAdDidShowFailed(_ splashAd: BUSplashAd, error: Error) {
        print("1111111111111111111111, 广告展示失败")
        loadAdOver()
    }

    // 广告渲染完成
    func splashAdRenderSuccess(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告渲染完成")
    }

    // 广告渲染失败
    func splashAdRenderFail(_ splashAd: BUSplashAd, error: BUAdError?) {
        print("1111111111111111111111, 广告渲染失败")
        loadAdOver()
    }

    // 广告展示
    func splashAdDidShow(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告展示")
    }

    // 广告控制器被关闭
    func splashAdViewControllerDidClose(_ splashAd: BUSplashAd) {
        print("1111111111111111111111, 广告控制器被关闭")
        loadAdOver()
    }

    // 其他控制器被关闭
    func splashDidCloseOtherController(_ splashAd: BUSplashAd, interactionType: BUInteractionType) {
        print("1111111111111111111111, 其他控制器被关闭")
    }

    // 视频播放完成
    func splashVideoAdDidPlayFinish(_ splashAd: BUSplashAd, didFailWithError error: Error?) {
        print("1111111111111111111111, 视频播放完成")
        loadAdOver()
    }
    
    @objc func loadAdOver() {
        toFlutter(method:"loadAdOver",arguments: "200")
    }
    
    @objc func toFlutter(method: String,arguments: Any?) {
        bridgeChannel?.invokeMethod(method, arguments: arguments) { (result) in

        }
    }
}
